package logger

import (
	"fmt"
	"gitee.com/hilaoyu/go-basic-utils/utils"
	"gopkg.in/natefinch/lumberjack.v2"
	"io/ioutil"
	"log"
	"path/filepath"
)

var (
	LogerTrace   *log.Logger                                                         // 记录所有日志
	LogerInfo    *log.Logger                                                         // 重要的信息
	LogerWarning *log.Logger                                                         // 需要注意的信息
	LogerError   *log.Logger                                                         // 非常严重的问题
	LogerRaw     *log.Logger                                                         // 原始日志
	LogPrefix    string                                                              // 日志前辍
	LogPath      string      = filepath.Join(utils.GetSelfPath(), "logs", "log.txt") //日志目录
)

func Init(logPrefix ...string) {
	if len(logPrefix) > 0 {
		LogPrefix = logPrefix[0]
	}
	prefix := LogPrefix
	if "" != prefix {
		prefix += ": "
	}
	logWriter := &lumberjack.Logger{
		Filename:   LogPath,
		MaxSize:    500, // megabytes
		MaxBackups: 3,
		MaxAge:     28,   //days
		Compress:   true, // disabled by default
	}

	if nil == LogerTrace {
		LogerTrace = log.New(ioutil.Discard,
			prefix+"TRACE: ",
			log.Ldate|log.Ltime|log.Lshortfile)
	}

	if nil == LogerInfo {
		LogerInfo = log.New(logWriter,
			prefix+"INFO: ",
			log.Ldate|log.Ltime|log.Lshortfile)
	}
	if nil == LogerWarning {
		LogerWarning = log.New(logWriter,
			prefix+"WARNING: ",
			log.Ldate|log.Ltime|log.Lshortfile)
	}
	if nil == LogerError {
		LogerError = log.New(logWriter,
			prefix+"ERROR: ",
			log.Ldate|log.Ltime|log.Lshortfile)
	}
	if nil == LogerRaw {
		LogerRaw = log.New(logWriter, prefix, 0)
	}
}

func LogInfo(message string, err error) {
	fmt.Println(message, err)
	LogerInfo.Println(message, err)
}

func LogWrong(message string, err error) {
	fmt.Println(message, err)
	LogerWarning.Println(message, err)
}

func LogErr(message string, err error) {
	fmt.Println(message, err)
	LogerError.Println(message, err)
}
func LogTrace(message string, err error) {
	fmt.Println(message, err)
	LogerTrace.Println(message, err)
}

func LogErrExit(message string, err error) {
	LogErr(message, err)
	panic("stop on error")
}
func LogRaw(message string) {
	fmt.Println(message)
	LogerRaw.Println(message)
}
